package com.dq.service.order.impl;

import com.alibaba.fastjson.JSONObject;
import com.dq.domain.sys.user.center.UserAccountStaffUser;
import com.dq.exception.customException.AdminException;
import com.dq.vo.Vo;
import com.dq.domain.orders.Orders;
import com.dq.domain.orders.UserOrder;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.dto.OrgStatisticeDto;
import com.dq.repository.BaseRepositories;
import com.dq.service.order.UserOrderService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author liuhui
 * @date 2019/12/2 0002 15:00:55
 */
@Service
public class UserOrderServiceImpl extends BaseRepositories implements UserOrderService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<OrgStatisticeDto> statisticsUserOrder(Long beginTime,Long endTime) {
        StringBuilder sql = new StringBuilder("select o.org_id as orgId,sum(oi.number) as num from order_info oi INNER JOIN orders o on o.id = oi.orders_id where o.dtype = 'UserOrder' and (o.status = 1 or o.status = 2)" +
                "and o.create_time &gt;=" +beginTime+"and o.create_time &lt;="+
                " GROUP BY o.org_id");
        Query query = entityManager.createNativeQuery(sql.toString());
        List rows = query.getResultList();
        List<OrgStatisticeDto> userOrderCountObjList = new ArrayList<>();
        for (Object row : rows) {
            Object[] cells = (Object[]) row;
            OrgStatisticeDto userOrderCountObj = new OrgStatisticeDto();
            userOrderCountObj.setOrgId(Long.parseLong(cells[0].toString()));
            userOrderCountObj.setNum(Long.parseLong(cells[1].toString()));
            userOrderCountObjList.add(userOrderCountObj);
        }
        return userOrderCountObjList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserOrder update(UserOrder userOrder) throws AdminException {

        userOrder.setLastModifyTime(System.currentTimeMillis());
        SysUser user = sysUserService.getUser();
        userOrder.setUpdateUser(user);

        entityManager.merge(userOrder);

        if(userOrder.getDeleted()) {
//            List<UserAccountStaffUser> userAccountStaffUserList = userOrderStaffUserRepository.findByUserOrderAndDeletedFalse(userOrder);
            List<UserAccountStaffUser> userAccountStaffUserList = new ArrayList<>();
            for (UserAccountStaffUser userAccountStaffUser : userAccountStaffUserList) {
                /*userAccountStaffUser.setLastModifyTime(System.currentTimeMillis());
                userAccountStaffUser.setUpdateUser(user);

                userAccountStaffUser.setDeleted(true);*/

                entityManager.merge(userAccountStaffUser);
            }
        }

        entityManager.flush();

        return userOrder;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Vo distributionRatio(Long id,String test) throws AdminException {
        if("".equals(test)){
            throw new AdminException("请填写比例");
        }
        JSONObject jsonInfo = JSONObject.parseObject(test);
        Iterator<Map.Entry<String, Object>> iter = jsonInfo.entrySet().iterator();
        List<UserAccountStaffUser> list = new ArrayList<>();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            System.out.println(entry.getKey().toString());
//            UserAccountStaffUser userAccountStaffUser = userOrderStaffUserRepository.findByDeletedFalseAndUserOrderIdAndStaffUserId(id,Long.parseLong(entry.getKey().toString()));
            UserAccountStaffUser userAccountStaffUser = new UserAccountStaffUser();
            if(entry.getValue() == null || "".equals(entry.getValue().toString())){
                throw new AdminException("请填写比例");
            }
            System.out.println(entry.getValue().toString());
            BigDecimal proportion = BigDecimal.valueOf(Long.parseLong(entry.getValue().toString()));
            userAccountStaffUser.setProportion(proportion.divide(new BigDecimal(100),2, RoundingMode.HALF_UP));
            list.add(userAccountStaffUser);
        }
        if(list.size()>0){
            userOrderStaffUserRepository.saveAll(list);
            Orders orders = dao.get(Orders.class,id);
            orders.setIsDistribution(true);
            dao.save(orders);
        }
        return new Vo(HttpStatus.OK);
    }
}
